using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Colman.Rpg.Connection;
using Colman.Rpg.Messaging;
using Colman.Rpg.Battles;

namespace Colman.Rpg.Pvp
{
    /// <summary>
    /// Displays the battle chat room.
    /// </summary>
    public partial class ChatForm : ConnectionAwareForm
    {
        private string CurrentUserSelected = string.Empty;
        Player myPlayerData;

        /// <summary>
        /// Default Constructor
        /// </summary>
        public ChatForm()
        {
            InitializeComponent();            
        }

        /// <summary>
        /// Send Message To Specific User
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            // if text typed
            if (txtMessageToSend.Text != string.Empty)
            {
                // send message to selected user in the user list
                ClientEndPoint.Instance.SendMessage(new ChatMessageRequest(txtMessageToSend.Text, CurrentUserSelected ,btnChooseColor.BackColor));
                txtMessageToSend.Clear();
            }
        }

        /// <summary>
        /// Send Message To All Users
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSendToAll_Click(object sender, EventArgs e)
        {
            // if text typed
            if (txtMessageToSend.Text != string.Empty)
            {
                // send message to all users in the user list
                ClientEndPoint.Instance.SendMessage(new ChatMessageRequest(txtMessageToSend.Text, btnChooseColor.BackColor));
                txtMessageToSend.Clear();
            }
        }

        /// <summary>
        /// Changing the user Fore Color
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChooseColor_Click(object sender, EventArgs e)
        {
            // creates color dialog
            ColorDialog clDlg = new ColorDialog();
            
            // activate the color dialog and check the result
            if (clDlg.ShowDialog() == DialogResult.OK)
            {
                // change user fore color
                btnChooseColor.BackColor = clDlg.Color;
                txtMessageToSend.ForeColor = clDlg.Color;
            }
        }

        /// <summary>
        /// Raises when message recived from the server
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OnMessageReceived(object sender, MessageReceivedEventArgs e)
        {
            // handle chat message
            #region Handle ChatMessageResponse
            if (e.Message is ChatMessageResponse)
            {
                ChatMessageResponse recived = (ChatMessageResponse)e.Message;
                
                // print the recived message into the messages window
                txtMessages.SelectionColor = recived.MessageColor;

                if (recived.IsPrivate)
                {
                    txtMessages.SelectionFont = new Font(new FontFamily(this.Font.Name), 10, FontStyle.Italic);
                    txtMessages.AppendText("Private Message From " + recived.Sender + " Says:\n\t" + recived.MessageBody + "\n");
                }
                else
                {
                    txtMessages.SelectionFont = new Font(new FontFamily(this.Font.Name), 10, FontStyle.Regular);
                    txtMessages.AppendText(recived.Sender + " Says:\n\t" + recived.MessageBody + "\n");
                }
            }
            #endregion
            
            // handle PVP creation
            #region Handle FightPlayerResponse
            else if (e.Message is FightPlayerResponse)
            {
                FightPlayerResponse received = (FightPlayerResponse)e.Message;
                
                // if message is for new game
                switch (received.ResponseOperation)
                {
                    case PvpFightRequestStage.Ask:
                        // request to begin new game
                        if (MessageBox.Show(String.Format("{0} Wants To Challange You, Do You Accept ?", received.Opponent.Name), "New Challange", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                        {
                            // accept the game request
                            ClientEndPoint.Instance.SendMessage(new FightPlayerRequest(received.Opponent.Name, PvpFightRequestStage.Accept));

                            btnCreateGame.Enabled = false;

                            // start the game
                            BattleForm battleForm = new BattleForm();
                            battleForm.Player = myPlayerData;
                            battleForm.Opponent = received.Opponent;
                            battleForm.ShowDialog(this);
                            btnCreateGame.Enabled = true;

                        }
                        else
                        {
                            // decline the game request
                            ClientEndPoint.Instance.SendMessage(new FightPlayerRequest(received.Opponent.Name, PvpFightRequestStage.Decline));
                        }
                        break;
                    case PvpFightRequestStage.Accept:
                        // if game accepted 
                        // start the game
                        BattleForm btlFrm = new BattleForm();
                        btlFrm.Player = myPlayerData;
                        btlFrm.Opponent = received.Opponent;
                        btlFrm.ShowDialog(this);
                        btnCreateGame.Enabled = true;
                        break;
                    case PvpFightRequestStage.Decline:
                        // game declined, show appropiate message
                        MessageBox.Show(String.Format("Request For New Game With {0} Was Declined :(", received.Opponent.Name), "New Challange", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                        btnCreateGame.Enabled = true;
                        break;
                    case PvpFightRequestStage.AutoDecline:
                        // too powerful or weak for foe, show appropiate message
                        MessageBox.Show(String.Format("You can not fight {0}, as they are either too powerful or weak for you to defeat.", received.Opponent.Name), "New Challange", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                        btnCreateGame.Enabled = true;
                        break;
                }
            }
            #endregion

            // handle new player data arrivel
            #region Handle GetConnectedUsersRespone
            else if (e.Message is GetConnectedUsersResponse)
            {
                GetConnectedUsersResponse recived = (GetConnectedUsersResponse)e.Message;

                // creating the user list
                lstUsers.Items.Clear();

                foreach (Player user in recived.ConnectedUsers)
                {
                    string[] data = new string[] { user.Name, user.HP.ToString(), user.AP.ToString(), user.DP.ToString(), user.XP.ToString(), user.Level.ToString(), user.Weapon.Name, user.Armor.Name };
                    ListViewItem addedItem = lstUsers.Items.Add(new ListViewItem(data));

                    if (user.IsInBattile)
                    {
                        addedItem.ForeColor = Color.Gray;
                    }
                    else
                    {
                        addedItem.ForeColor = Color.Black;
                    }

                    if (user.Name == ClientEndPoint.Instance.UserName)
                    {
                        myPlayerData = user;
                    }
                }

                // serialize last selected
                #region Serialize
                lstUsers.Sort();
                int index = 0;

                foreach (ListViewItem user in lstUsers.Items)
                {
                    if (user.Text == CurrentUserSelected)
                    {
                        lstUsers.Items[index].Selected = true;

                        break;
                    }

                    index++;
                }
                #endregion
            }
            #endregion

            // handle player levelling up
            #region Handle PlayerLevelledUpResponse
            else if (e.Message is PlayerLevelledUpResponse)
            {
                PlayerLevelledUpResponse response = (PlayerLevelledUpResponse)e.Message;

                if (response.Player.Name == ClientEndPoint.Instance.UserName)
                {
                    CharacterSheetForm form = new CharacterSheetForm();
                    form.SetPlayer(response.Player, response.PointsOwedForLevellingUp);

                    form.ShowDialog(this);
                }
            }
            #endregion
        }

        /// <summary>
        /// Handle Selection user changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstUsers.SelectedItems.Count > 0)
            {
                if (lstUsers.SelectedItems[0].Text == myPlayerData.Name)
                {
                    btnSend.Enabled = false;
                    btnCreateGame.Enabled = false;
                }
                else if (lstUsers.SelectedItems[0].ForeColor == Color.Gray)
                {
                    btnCreateGame.Enabled = false;
                    btnSend.Enabled = true;
                }
                else
                {
                    btnSend.Enabled = true;
                    btnCreateGame.Enabled = true;
                }

                CurrentUserSelected = lstUsers.SelectedItems[0].Text;
            }
            else
            {
                btnSend.Enabled = false;
                btnCreateGame.Enabled = false;

                CurrentUserSelected = string.Empty;
            }

        }

        /// <summary>
        /// Send request from new PVP game
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateGame_Click(object sender, EventArgs e)
        {
            ClientEndPoint.Instance.SendMessage(new FightPlayerRequest(CurrentUserSelected,PvpFightRequestStage.Ask));
            btnCreateGame.Enabled = false;
        }
        
        /// <summary>
        /// Joins to new chat room
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChatForm_Load(object sender, EventArgs e)
        {
            ClientEndPoint.Instance.SendMessage(new ChatMessageRequest("I Have Joined The Chat :)", Color.Black));
        }

    }
}
